<template>
  <el-dialog :title="showTitle" :visible="showDialog" @close="close">
    <el-form v-if="formGettingVisible" ref="addDept" :model="formData" :rules="rules" label-width="120px">
      <el-form-item prop="name" label="部门名称">
        <el-input
          v-model="formData.name"
          placeholder="2-10个字符"
          style="width: 80%"
          size="mini"
        />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input
          v-model="formData.code"
          placeholder="2-10个字符"
          style="width: 80%"
          size="mini"
        />
      </el-form-item>
      <el-form-item prop="managerId" label="部门负责人">
        <el-select
          v-model="formData.managerId"
          placeholder="请选择负责人"
          style="width: 80%"
          size="mini"
        >
          <!-- value为存储字段 与select中v-model绑定内容对应-->
          <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input
          v-model="formData.introduce"
          placeholder="1-100个字符"
          style="width: 80%"
          size="mini"
          type="textarea"
        />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button size="mini" type="primary" @click="btnOK">确定</el-button>
            <el-button size="mini" @click="close">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { getDepartment, getManagerList, addDepartment, getDepartmentDetail, updateDepartment } from '@/api/department'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    currentNodeId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      formGettingVisible: true,
      resetTimeout: null,
      managerList: [],
      formData: {
        code: '',
        introduce: '',
        managerId: '',
        name: '',
        pid: ''
      },
      rules: {
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '部门编码的长度为2-10个字符',
            trigger: 'blur'
          },
          {
            trigger: 'blur',
            validator: async(rule, value, callback) => {
              let res = await getDepartment()
              // 判断是否为编辑模式
              if (this.formData.id) {
                // 编辑场景 过滤出与自身id不同的数据进行比较
                res = res.filter(item => item.id !== this.formData.id)
              }
              if (res.some(item => item.code === value)) {
                callback(new Error('部门中已有该编码'))
              } else {
                callback()
              }
            }
          }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '部门介绍的长度为1-100个字符',
            trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '部门名称的长度为2-10个字符',
            trigger: 'blur'
          },
          {
            trigger: 'blur',
            validator: async(rule, value, callback) => {
              let res = await getDepartment()
              // 判断是否为编辑模式
              if (this.formData.id) {
                // 编辑场景 过滤出与自身id不同的数据进行比较
                res = res.filter(item => item.id !== this.formData.id)
              }
              if (res.some(item => item.name === value)) {
                callback(new Error('部门中已有该名称'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  watch: {
    showDialog(newValue) {
      if (newValue) {
        this.formGettingVisible = true
      } else {
        this.resetTimeout = setTimeout(() => {
        // bug：点完编辑后，id会存在，返回再点击添加，id没清空
          this.formData = {
            code: '',
            introduce: '',
            managerId: '',
            name: '',
            pid: ''
          }
          this.formGettingVisible = false
        }, 500)
      }
    }
  },
  beforeDestroy() {
    if (this.resetTimeout) {
      clearTimeout(this.resetTimeout)
    }
  },
  created() {
    this.getManagerList()
  },
  methods: {
    close() {
      // bug：点完编辑后，id会存在，返回再点击添加，id没清空
      // 原因：resetFields 只能重置模版中绑定的数据，其他需要手动置空
      this.$emit('update:showDialog', false)
    },
    async getManagerList() {
      this.managerList = await getManagerList()
    },
    btnOK() {
      this.$refs.addDept.validate(async isOK => {
        if (isOK) {
          let msg = '新增'
          // 判断是否是编辑模式
          if (this.formData.id) { // 编辑场景
          // 只有this.formData有id的时候才执行，因此this.formData中一定有id可以传给对应接口
            msg = '更新'
            await updateDepartment(this.formData)
          } else { // 新增场景 后面新加的值会替换前面的值 pid由''变成被赋值后的值
            await addDepartment({ ...this.formData, pid: this.currentNodeId
            })
          }
          // 通知父组件更新
          this.$emit('updateDepartment')
          this.$message.success(`${msg}部门成功`)
          this.close()
        }
      })
    },
    async getDepartmentDetail() {
      this.formData = await getDepartmentDetail(this.currentNodeId)
    }
  }
}
</script>
